Golang : Setting variable value with ldflags
This short tutorial will demonstrate how to initialize a variable value during runtime at the stage of compilation/linking. Go linker has an option to set the value of an uninitialised string variable:
-X symbol value
Set the value of an otherwise uninitialized string variable.
The symbol name should be of the form importpath.name,
as displayed in the symbol table printed by "go tool nm".
For example :
package main
import "fmt"
var str string
func main() {
fmt.Println(str)
}
and execute the program with -ldflags
to initialize the str variable value
$ go run -ldflags "-X main.str abc" main.go
or if you prefer, build it first into executable binary :
$ go build -ldflags "-X main.str 'abc'" main.go && ./main
Output :
abc
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Decode XML data from RSS feed
+40.1k Golang : UDP client server read write example
+6.8k Android Studio : Hello World example
+11.3k Golang : Intercept and process UNIX signals example
+37.5k Golang : Converting a negative number to positive number
+8.3k Golang : Count leading or ending zeros(any item of interest) example
+47.8k Golang : Convert int to byte array([]byte)
+10.5k Golang : Select region of interest with mouse click and crop from image
+22.1k Golang : Repeat a character by multiple of x factor
+11.9k Golang : Convert decimal number(integer) to IPv4 address
+22.9k Golang : Test file read write permission example
+14.5k Golang : Overwrite previous output with count down timer